package dev.werillib.camera

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import dev.werillib.android.PermissionUtil
import dev.werillib.android.ToastUtil
import dev.werillib.camera.TakePhotoConstant.Companion.REQUEST_CODE_FROM_CAPTURE
import dev.werillib.camera.TakePhotoConstant.Companion.REQUEST_CODE_FROM_GALLERY
import dev.werillib.camera.TakePhotoConstant.Companion.TAKEPHOTO_PERMISSIONS
import dev.werillib.utils.BitmapUtil
import dev.werillib.utils.FileUtil
import dev.werillib.utils.d
import top.zibin.luban.OnCompressListener
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

open class TakePhotoActivity : AppCompatActivity(), TakePhoto, TakePhotoResultListener {
    override fun takeSuccess(file: File) {

    }

    override fun takeFail() {

    }

    lateinit var takePhoto: TakePhoto
    private lateinit var takePhotoResultListener: TakePhotoResultListener
    private var photoPath: String? = null
    private var compress = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        takePhoto = this
        takePhotoResultListener = this
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_FROM_GALLERY -> {
                    if (data != null && data.data != null) {
                        val proj = arrayOf(MediaStore.Images.Media.DATA)
                        val cursor = contentResolver.query(data.data!!, proj, null, null, null)
                        if (cursor != null && cursor.moveToFirst()) {
                            val columnIndex =
                                cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                            photoPath = cursor.getString(columnIndex)
                            if (photoPath == null) {
                                photoPath = FileUtil.getFilePathByUri(this, data.data!!)
                            }
                        } else {
                            photoPath = data.data!!.path
                        }
                        cursor?.close()

                        if (FileUtil.exists(photoPath)) {
                            setBack(File(photoPath), compress)
                        } else {
                            takePhotoResultListener.takeFail()
                        }
                    }
                }

                REQUEST_CODE_FROM_CAPTURE -> {
                    if (data != null) {
                        var imagePhoto: Bitmap? = null
                        if (data.data != null || data.extras != null) { //防止没有返回结果
                            val uri = data.data
                            if (uri != null) {
                                imagePhoto = BitmapFactory.decodeFile(uri.path) //拿到图片
                            }
                            if (imagePhoto == null) {
                                val bundlePic = data.extras
                                if (bundlePic != null) {
                                    imagePhoto = bundlePic.get("data") as Bitmap
                                } else {
                                    takePhotoResultListener.takeFail()
                                }
                            }
                        } else {
                            d("get picture fail")
                            takePhotoResultListener.takeFail()
                        }
                        if (imagePhoto != null) {
                            photoPath = FileUtil.getLocalPath() + "temp_" +
                                    SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
                                        .format(Date()) + ".jpg"
                            BitmapUtil.saveImage(imagePhoto, photoPath!!)
                            imagePhoto.recycle()
                            setBack(File(photoPath), compress)
                        }
                    }
                }
            }
        } else {
            takeFail()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            when (requestCode) {
                REQUEST_CODE_FROM_GALLERY -> onPickFromGallery(compress)
                REQUEST_CODE_FROM_CAPTURE -> onPickFromCapture(compress)
            }
        }
    }

    //从相册选取
    override fun onPickFromGallery(compress: Boolean) {
        this.compress = compress
        if (!PermissionUtil.checkSelfPermission(this, TAKEPHOTO_PERMISSIONS)) {
            PermissionUtil.requestPermission(this, TAKEPHOTO_PERMISSIONS, REQUEST_CODE_FROM_GALLERY)
        } else {
            val innerIntent = Intent()
            innerIntent.action = Intent.ACTION_PICK
            innerIntent.type = "image/*"
            val wrapperIntent = Intent.createChooser(innerIntent, "相册")
            startActivityForResult(wrapperIntent, REQUEST_CODE_FROM_GALLERY)
        }
    }

    //从相机选取
    override fun onPickFromCapture(compress: Boolean) {
        this.compress = compress
        if (!PermissionUtil.checkSelfPermission(this, TAKEPHOTO_PERMISSIONS)) {
            PermissionUtil.requestPermission(this, TAKEPHOTO_PERMISSIONS, REQUEST_CODE_FROM_CAPTURE)
        } else {
            val state = Environment.getExternalStorageState()
            if (state == Environment.MEDIA_MOUNTED) {
                val getImageByCamera = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                startActivityForResult(getImageByCamera, REQUEST_CODE_FROM_CAPTURE)
            } else {
                ToastUtil.toast(this, "请插入SD卡！")
            }
        }
    }

    private fun setBack(file: File, compress: Boolean) {
        when (compress) {
            true -> {
                Compress.compressImage(this, file, object : OnCompressListener {
                    override fun onStart() {}

                    override fun onSuccess(file: File) {
                        takePhotoResultListener.takeSuccess(file)
                    }

                    override fun onError(e: Throwable) {
                        takePhotoResultListener.takeFail()
                    }
                })
            }
            false -> {
                takePhotoResultListener.takeSuccess(file)
            }
        }
    }
}